package com.more.offer.threadtest.aqstest;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.Condition;

/**
 * @author pinoc
 * @date 2021/6/26 修改1
 * @description 使用AQS 模拟一个生产者和消费者
 */
public class ProductAndConsumerDemoTest {

	private final static NonReentrantLock lock = new NonReentrantLock();
	private final static Condition notFull = lock.newCondition();
	private final static Condition notEmpty = lock.newCondition();

	private final static Queue<String> queue = new LinkedBlockingDeque<>();
	public static final int queueSize = 20;

	public static void main(String[] args) {
		//生产者线程
		Thread producer = new Thread(() -> {
			lock.lock();
			try{
				while(queue.size() == queueSize){
					notEmpty.wait();
				}

				queue.add("element");
				notFull.signalAll();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		});

		Thread consumer = new Thread(() -> {
			lock.lock();
			try{
				while(queue.size() == 0) {
					notFull.await();
				}

				String poll = queue.poll();
				System.out.println("consumer poll one element: " + poll);

				notEmpty.signalAll();
			}catch (Exception e) {
				e.printStackTrace();
			}finally {
				lock.unlock();
			}
		});

		producer.start();
		consumer.start();
	}
}
